import datetime
import socket
import time
from urllib.parse import quote_plus
import psutil
import pymongo
import requests
from pymongo import MongoClient


def get_mac_address():
    """
    获取MAC地址
    :return:
    """
    interfaces = psutil.net_if_addrs()
    for interface_name, addresses in interfaces.items():
        for address in addresses:
            if address.family == psutil.AF_LINK:
                return address.address


if __name__ == '__main__':
    user_flag = input("请输入大写姓名拼音(HOUJUNHAO): ")
    response = requests.get('https://checkip.amazonaws.com')
    ip_address = response.text.replace("\n", "")
    username = socket.gethostname()
    mac_address = get_mac_address()

    ip = "222.89.84.32"
    db_name = "py_policy"
    port = "27027"
    name = "admin"
    pwd = "mongo@yc66.com"
    # 连接到MongoDB
    client = MongoClient(
        f'mongodb://{quote_plus(name)}:{quote_plus(pwd)}@222.89.84.32:27027/?authMechanism=DEFAULT&authSource=admin')

    # 选择数据库
    db = client['py_policy']

    # 选择集合
    collection = db['user_info']

    user_info = {
        "username": username,
        "ip_address": ip_address,
        "mac_address": mac_address,
    }

    res_data = collection.find_one(filter=user_info)
    if res_data is None:
        user_info = {
            "username": username,
            "user_flag": user_flag,
            "ip_address": ip_address,
            "mac_address": mac_address,
            "creater_time": datetime.datetime.now(),
            "upload_time": datetime.datetime.now()
        }

        # 插入单个文档
        collection.insert_one(user_info)

        print("录入成功，请手动关闭程序... ...")
    else:
        print("已存在用户信息... ...")

    time.sleep(60)
